package com.zheng.admin.interceptor;

import com.zheng.admin.common.Consts;
import com.zheng.admin.entity.PermSubject;
import com.zheng.admin.exception.AdminSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zhangchaozheng on 15-3-11.
 */
public class SecurityInterceptor implements HandlerInterceptor {

    private final static Logger LOG = LoggerFactory.getLogger(SecurityInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        LOG.info("[SecurityInterceptor] security interceptor begin. uri={}", requestURI);

        // 2.检查是否登陆
        HttpSession session = request.getSession(false);
        if (session == null) {
            throw new AdminSystemException("user.not.login", "用户未登录");
        }
        Integer userId = (Integer) session.getAttribute(Consts.SESS_USER_ID);
        PermSubject permSubject = (PermSubject) session.getAttribute(Consts.SESS_PERM_SUB);
        if (userId == null) {
            throw new AdminSystemException("user.not.login", "用户未登录");
        }
        String prefix = requestURI.endsWith(".html") ? "menu" : "opt";
        StringBuffer opBuff = new StringBuffer(prefix + ":");

        String[] requestURIArr = org.apache.commons.lang3.StringUtils.split(requestURI,"/");
        for (String item : requestURIArr) {
            opBuff.append(item).append(":");
        }
        opBuff.delete(opBuff.length() - 1, opBuff.length());
        boolean isPermitted = permSubject.isPermitted(opBuff.toString());

        if (!isPermitted) {
            LOG.info("[SecurityInterceptor] no permitted. url={}", requestURI);
            throw new AdminSystemException("user.login.no.permitted", "没有权限");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}